use anyhow::{Context, Result};
use reqwest::Client;
use salvo::http::{header, Response};
use std::time::Duration;

/// Download file from URL and return as stream
pub async fn download_file(url: &str) -> Result<Response> {
    let client = Client::builder()
        .timeout(Duration::from_secs(30))
        .build()
        .context("Failed to create HTTP client")?;

    let response = client
        .get(url)
        .send()
        .await
        .context("Failed to send request")?;

    if !response.status().is_success() {
        return Err(anyhow::anyhow!(
            "Request failed with status: {}",
            response.status()
        ));
    }

    let content_type = response
        .headers()
        .get(reqwest::header::CONTENT_TYPE)
        .and_then(|h| h.to_str().ok())
        .unwrap_or("application/octet-stream")
        .to_string();

    let stream = response.bytes_stream();

    let mut res = Response::new();
    res.headers_mut()
        .insert(header::CONTENT_TYPE, content_type.parse().unwrap());
    res.stream(stream);

    Ok(res)
}
